import React from 'react';
import { Spin, Table } from 'antd';
import Immutable from 'immutable';
const { is, fromJS } = Immutable;
import { WeaErrorPage, WeaTools } from 'ecCom';
import Title from './Title';
import { formatData } from '../../util/common';
//内容组件
class EContent extends React.Component {
    constructor(props) {
        super(props);
        const currentTab = props.edata.currenttab || props.edata.tabids[0];
        this.state = {
            tabdata: props.edata.data[currentTab],
            currentTab: currentTab,
            refresh: false,
        }
        this.handleTabData = this.handleTabData.bind(this);
    }
    componentWillReceiveProps(nextProps){
        if(!is(fromJS(nextProps),fromJS(this.props))){
            const currentTab = nextProps.edata.currenttab || nextProps.edata.tabids[0];
            this.setState({
                tabdata: nextProps.edata.data[currentTab],
                currentTab: currentTab,
                refresh: false,
            }); 
        }
    }
    shouldComponentUpdate(nextProps, nextState){
        return !is(fromJS(this.state), fromJS(nextState)) || !is(fromJS(this.props),fromJS(nextProps))
    }
    handleTabData(tabid){
        const { edata, config } = this.props;
        const { params } = config;
        const { currentTab } = this.state;
        this.setState({
            currentTab: tabid,
            tabdata: edata.data[tabid],
            refresh: tabid === currentTab,
        });
        setTimeout(()=>{
            this.setState({
                refresh: false,
            });
        },100);
    }
    render() {
        const { config, edata, handleRefresh, handleDelete } = this.props;
        const { tabdata, currentTab, refresh } = this.state; 
        const { eid } = config.item;
        const { tabids, titles, esetting, counts } = edata;
        let contentHtml = tabdata && tabdata.length ? <Table columns={formatData(tabdata[0], esetting)} showHeader={false} pagination={false} dataSource={tabdata} size="small"/> : <div/>;
        const _titleProps = {
            currentTab,
            config,
            titles,
            tabids,
            counts,
            handleRefresh,
            handleDelete,
            handleTabData: this.handleTabData
        }
        if(refresh) contentHtml = <Spin>{contentHtml}</Spin>
        return <div>
            <Title {..._titleProps}/>
            <div className="tabContant" id={`tabcontant_${eid}`}>
                {contentHtml}
            </div>
         </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage msg = { hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" }/>
        );
    }
}
EContent = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(EContent);
export default EContent;
